<template>
  <CommonCard title="今日订单量" :count="orderToday">
    <template #main>
      <!-- 准备容器(必须带有高度) -->
      <div class="main" ref="mainRef"></div>
    </template>
    <!-- 下半部分 -->
    <template #buttom>
      <span class="mr-10">昨日销售额</span>
      <span>{{ echartStore.storeEchartData.orderLastDay }}</span>
    </template>
  </CommonCard>
</template>

<script setup lang="ts">
// 导入store
import useEchartStore from '@/stores/echart'
import type { EChartsType } from 'echarts'
import { onMounted, ref, watch, computed, onUnmounted } from 'vue'
import { $echarts } from '@/plugins/echarts'

// 导入类型
// 获取仓库实例
const echartStore = useEchartStore()
const mainRef = ref<HTMLDivElement>()

// 声明一个变量存储
let myChart = ref<EChartsType>()

const orderToday = computed(() => {
  return echartStore.storeEchartData.orderToday
})

// 将函数抽离出来
const resizeFun = () => {
  // console.log(111)
  myChart.value?.resize()
}

// 声明配置项
const initOption = () => ({
  tooltip: {}, // 鼠标划入的信息
  xAxis: {
    // x轴
    data: echartStore.storeEchartData.orderTrendAxis,
    show: false
  },
  yAxis: {
    show: false
  }, // y轴
  grid: {
    left: 0,
    right: 0,
    top: 0,
    bottom: 0
  },
  series: [
    {
      type: 'line',
      data: echartStore.storeEchartData.orderTrend,
      smooth: true, // 平滑
      itemStyle: {
        opacity: 0 //拐点
      },
      lineStyle: {
        opacity: 0 //
      },
      areaStyle: {
        // 折线区域
        color: 'hotpink'
      }
    }
  ]
})
// 在组件挂载时获取到dom元素
onMounted(() => {
  myChart.value = $echarts.init(mainRef.value as HTMLDivElement)
  // 传入配置项
  myChart.value.setOption(initOption())

  window.addEventListener('resize', resizeFun)
})

watch(orderToday, (newVal) => {
  if (newVal) {
    myChart.value?.setOption(initOption())
  }
})

// 在卸载组件时,清除绑定的函数
onUnmounted(() => {
  // 住: 如果不清楚这个函数,则会在其他界面也会触发
  window.removeEventListener('resize', resizeFun)
})
</script>

<style lang="scss" scoped>
.main {
  height: 50px;
}
</style>
